package com.my.test.goods.inteceptor;

import java.io.ByteArrayOutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org. springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class GlobalLogInteceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setAttribute("startTime", System.currentTimeMillis());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Map<String,String[]> params = request.getParameterMap();
			System.out.println(params.toString());
			long start = (Long)request.getAttribute("startTime");
			if(null!=ex){
				System.out.println(ex.getMessage());
				String stackTrace = getStackTrace(ex);
				System.out.println(stackTrace);
			}
			System.out.println(request.getRequestURL().toString()+"："+handlerMethod.getMethod().toString()+",耗时:"+(System.currentTimeMillis()-start));
		}
	}
	
	public static String getStackTrace(Throwable ex) {
		ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream();
		try {
			ex.printStackTrace(new java.io.PrintWriter(buf, true));
			return buf.toString();
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				buf.close();
			} catch (Exception a) {
			}
		}
	}

}
